const App = getApp();
import MYJS from '../../utils/myinit.js';
// 枚举类：支付方式
import PayTypeEnum from '../../utils/enum/order/PayType';
Page({
    data: {
      isLogin:false,
      qaprice:0,
      checkIdsStr:'',
      checkIdsArr:[],
      goodPriceArr:{}, //点击了那个存放那个商品价格，如 goodPriceArr['p_111']=21;
      allPrice:0,
      showSubmitKey:1,  // 1：显示选择的试卷，2：显示选择的试卷并提交

      qaList:[],
      userObjArr:[],

      balance:0,
      lastBalance:0,

      needMoney:0,
      useYUmoney:0,
      useWXmoney:0,

      isRunningSubmit: false,
    },
    onLoad(options) {
      this.setData({
        showSubmitKey:options.key
      });
    },
    onShow(){
      this.setData({isLogin: App.checkIsLogin()});
      if(this.data.isLogin){
        var wxapp=wx.getStorageSync('wxapp');
        var jsonString = wx.getStorageSync('checkIdsStr');
        if(jsonString){
          this.setData({checkIdsStr:jsonString, checkIdsArr:JSON.parse(jsonString), qaprice:wxapp['qa_intprice']});
          this.getQaList();
        }
        // 设置navbar标题、颜色
        App.setNavigationBar();
        if(this.data.showSubmitKey==1){
          wx.setNavigationBarTitle({
            title: '已选择'
          });
        }
      }
      else{
        App.doLogin();
      }
    },
    /** 根据checkIds获取试卷列表 */
    getQaList(){
      let _this = this;
      App._get('askanswer/qbBoxListByOrder', {checkIdsStr:_this.data.checkIdsArr.join()}, result => {
        _this.setData({qaList:result.data.list, userObjArr:result.data.user, balance:result.data.user['balance']});
        var _goodPriceArr = this.data.goodPriceArr;
        for(let i in result.data.list){
          var obj = result.data.list[i];
          _goodPriceArr['p_'+obj['bq_id']] = obj['bq_price'];
        }
        _this.setData({goodPriceArr:_goodPriceArr});
        _this.mathMoney();
      });
    },
    /** 计算商品总价格 */
    getAllPrice(){
      var jsonString = wx.getStorageSync('checkIdsStr');
      var _goodPriceArr = this.data.goodPriceArr;
      var _allPrice = 0;
      if(jsonString){
        var checkIdsArr = JSON.parse(jsonString);
        if(checkIdsArr.length>0){
          for(let i in checkIdsArr){
            _allPrice += parseInt(_goodPriceArr['p_'+checkIdsArr[i]]);
          }
        }
      }
      this.setData({allPrice:_allPrice});
      return _allPrice;
    },
    /** 计算金额相关 */
    mathMoney(){
      //var needMoney = this.data.checkIdsArr.length * this.data.qaprice;
      var needMoney = this.getAllPrice();
      var useYUmoney = 0;
      var lastBalance = 0;
      var useWXmoney = needMoney;
      if(this.data.balance >= needMoney){
        useYUmoney = needMoney;
        useWXmoney = 0;
        lastBalance = MYJS.floatMathFun(this.data.balance, needMoney, '-');
      }
      if(this.data.balance < needMoney){
        useYUmoney = this.data.balance;
        useWXmoney = MYJS.floatMathFun(needMoney, this.data.balance, '-');
        lastBalance = 0;
      }
      this.setData({needMoney,useYUmoney,useWXmoney,lastBalance});
    },
    /** 删除订单中的试卷 */
    delQaBox(e){
      var qaid = e.currentTarget.dataset.qaid;
      let _this = this;
      MYJS.sx_confirm('确定删除？',function(){
        var nowCheckIdsArr = _this.data.checkIdsArr;
        var cnt = nowCheckIdsArr.indexOf(qaid+"");
        if(cnt > -1){
          nowCheckIdsArr.splice(cnt, 1);
          var nowCheckIdsStr = JSON.stringify(nowCheckIdsArr)
          _this.setData({checkIdsArr:nowCheckIdsArr, checkIdsStr:nowCheckIdsStr});
          wx.setStorageSync('checkIdsStr', nowCheckIdsStr);   //返回到大厅的时候，触发onshow函数
          //从数据列表中删除
          var nowQaList = [];
          for (let i in _this.data.qaList) {
            if (_this.data.qaList[i]['bq_id'] != qaid) {
              nowQaList.push(_this.data.qaList[i])
            }
          }
          _this.setData({qaList:nowQaList});
          _this.mathMoney();
        }
      })
    },
    /** 提交订单，唤醒支付 */
    runSubmintOrder(){
      if(App.checkIsLogin()){
        let _this = this
        if(this.data.isRunningSubmit==false){
          this.setData({isRunningSubmit:true});
          var checkIdsStr = _this.data.checkIdsArr.join();
          App._get('askanswer/submitQaOrder', {checkIdsStr:checkIdsStr}, result => {
                
                // 余额支付
                if (result.data.pay_type == PayTypeEnum.BALANCE.value) {
                  App.showSuccess(result.msg.success, () => {
                    _this.setData({isRunningSubmit:false});
                    _this.redirectToOrderIndex();
                  });
                }
                // 发起微信支付
                if (result.data.pay_type == PayTypeEnum.WECHAT.value) {
                  App.wxPayment({
                    payment: result.data.payment,
                    success: res => {
                      _this.setData({isRunningSubmit:false});
                      _this.redirectToOrderIndex();
                    },
                    fail: res => {
                      App.showError(result.msg.error, () => {
                        _this.setData({isRunningSubmit:false});
                        //_this.redirectToOrderIndex();
                      });
                    },
                  });
                }
          });
        }
      }
      else{
        App.doLogin();
      }
    },
    /**  正常完成下单之后的逻辑 */
    redirectToOrderIndex() {
      wx.setStorageSync('checkIdsStr', JSON.stringify([]));
      wx.setStorageSync('runQAlist', 'yes');
      wx.redirectTo({
        url: '/pages/studycenter/myorder',
      });
    },
});